//
// Content management
//

var gbTaskInfo = false; //

var guser = ''; //userhash
var gspace = ''; //spaceid

//
//
gaTasks = new Array(); 
var gdlm = '*|*';
var gdlm2 = '*||*';
var giBitWidth = 212;
var isCtrl = false; //Tack CTRL Key


$.ajaxSetup({
  timeout: 30000,
  cache: false,
  global: true,
});


// Init ---------------------------------------------------------------------------------------------

function init(){
  //Enable Ajax Indicator
$("#loading").bind("ajaxSend", function(){
   $(this).show();
 }).bind("ajaxComplete", function(){
   $(this).hide();
 });

  $.get('/user', function(data) {
    if (data != 'err_not_signed_in'){
	  adata = data.split(gdlm)
	  guser = adata[0]; //set userhash
	  $('#span_user').html(adata[1]);
	  init_space();
	} else {
	  $('#div_body').html('Not signed in - Redirecting to SignIn page...');
	  location.href="/signin?url=" + escape(location.href);
	}
});
}

function init_space(){
  space = location.href;
  if (space.indexOf('#')> -1){
	space = space.substr(space.indexOf('#')+1,100);
	if (parseInt(space) > -1)
	{
      gspace=""+parseInt(space);
      $('#div_space').hide('fast');
	}
  } 
  space_init_load();
  if (gspace == ''){
    space_init();
	$('#div_space').show('fast');
  } else {
    init_final();
  }
}

function set_space(pid){
  gspace=pid;
  $('#div_space').hide('fast');
  init_final();
}

function init_final(){
 
 //get space name
 $.get('/space/'+gspace, function(data) {
   document.title=data.split(gdlm)[0];
 });
 
 
 
 html_line(1,'FF1A00','Hot Stream: You are working on this task now.');
 html_line(2,'F3AE48','Warm Stream: Consider this as tasks to be done next.');
 html_line(2,'FFF298','From here one, task become more and more irrelevant...');


 // Catch Enter key when creating new task
 $('#ta_task_new').keyup(function(e) {
 //alert(e.keyCode);
 if(e.keyCode == 13) {
   task_create();
 }
 });


 //no animation when loading
 task_init();

 //update dates each minute
 setInterval(function(){ $(".span_bit_date").prettyDate(); }, 60000);

 //Tipsy
 $('#ta_task_new').tipsy({gravity: 'n'}); 

 //Track Enter Key
 $(document).keyup(function (e) { if(e.which == 17) isCtrl=false; }).keydown( function (e) { if(e.which == 17) isCtrl=true; } ); 


}

// HTML Creators  ---------------------------

function space_add(pid, pname, pdescription){
  html = '<div style="display:none;" id="space'+pid+'" class="div_space_class">'+
         '<a href="#'+pid+'" onClick="set_space(\''+pid+'\');">'+pname+'</a> '+ pdescription +
         '</div>';
  $('#div_spaces').prepend(html);
  $('#space'+pid).show('slow');
}

function task_add(pani, pid,ptext,powner,pcreated){
  ilength = gaTasks.push(pid);
  vWidth = (giBitWidth * ilength) + 'px';
  $('#div_body').css('width',vWidth);
  $('#div_html_line').css('width',vWidth);

  //create html
  html = '<div style="display:none;" class="div_col" id="col'+pid+'">' +
         '<div class="div_task" id="task'+pid+'">' +
         '<p class="p_task_caption" taskid="'+pid+'">'+ptext+'</p>' +
         '<button class="not_first_col" onClick="task_move(\''+pid+'\',\'+x\');">&larr; Now</button>' +
         '<button class="not_last_col" onClick="task_move(\''+pid+'\',\'-x\');">Later &rarr;</button>' +
         '<button onClick="task_del(\''+pid+'\');">Done</button>' +
         '<textarea id="ta_bit_new'+pid+'" original-title="Enter sub-tasks (bits). Think backwards: Start with the goal and enter each small step needed to reach it."></textarea>' +
         '<button id="btn_bit_new'+pid+'" onClick="bit_create('+pid+')">Update</button>' +
         '</div>' +
         '<div id="task_bits'+pid+'"></div>' +
         '<p class="p_task_footer"><b>History:</b> <a class="a_link" href="javascript:bit_init_deleted(\''+pid+'\');">Load</a>' +
         '<span style="visibility:hidden;" id="span_bit_close_del'+pid+'"> | ' +
         '<a class="a_link" href="javascript:bit_close_deleted(\''+pid+'\');">Close</a></span></p>' +
         '<div style="visibility:hidden;"  id="task_bits_deleted'+pid+'"></div>';
  $('#div_body').prepend(html);  //add html to board
  if (pani){
    $('#col'+pid).show('slow');  //make html visible
    task_style(pid);
  } else {
    $('#col'+pid).show(0);  //make html visible directly
  }

  $('#ta_bit_new'+pid).keyup(function(e) {
  if(e.keyCode == 13 && isCtrl == true) {
    id = pid;
    $('#btn_bit_new'+id).click();
  }
  });


  $('#ta_bit_new'+pid).focus();  //focus test area

  //AutoComplete disabled for now.
  //$('#ta_bit_new'+pid).autocomplete('/space/'+gspace+'/users');


  if (gbTaskInfo) {
    $('#ta_bit_new'+pid).tipsy({gravity: 'w'}); 
    gbTaskInfo = false;
  }

}

function bit_add(pani, ptaskid,pid,ptext,pauthor,pdate,pwhere){
  //modifier
  // if text starts with - or has less then 4 words, it is a bullet list
  sCSSClass = '';
  bBullet = false;
  try {
    
    if (ptext != ''){
      if ((ptext.substr(0,1) == '-' || ptext.split(" ").length < 4) && pwhere != 'deleted'){
        sCSSClass = 'div_bit_bullet';
		bBullet = true;
      }
    }
  } catch(err) {
    erro = 'not critical';
  }
  //disable buttons if bit is deleted
  sAttribDisabled = '';
  if (pwhere == 'deleted'){ sAttribDisabled = 'disabled="disabled"';}
  
  //create html
  html = '<div style="display:none;" class="div_bit '+sCSSClass+'" id="bit'+pid+'">' +
         '<p>';
	
  if (bBullet){html +='<button class="btn_done_bullet" onClick="bit_del(\''+ptaskid+'\',\''+pid+'\');">&#10004;</button>'; } //add mini button inside text for bullets
  html +=n2br(ptext);
  
  html +='</p>';
  
  html +='<span class="span_bit_creator">'+pauthor+'</span><span class="span_bit_date" title="'+pdate+'">'+pdate.substr(0,10)+'</span>' +
         '<button class="not_first" onClick="bit_move(\''+pid+'\',\''+ptaskid+'\',\'+x\');">&uarr; Now</button>';
  
  html +='<button class="not_last" '+sAttribDisabled+' onClick="bit_move(\''+pid+'\',\''+ptaskid+'\',\'-x\');">Later &darr;</button>' +
         '<cite class="cite_info cite_info_sort">i</cite>' +
         '<button '+sAttribDisabled+' onClick="bit_del(\''+ptaskid+'\',\''+pid+'\');">Done</button>';

  html +='</div>';

  if (pwhere == 'init'){
    $('#task_bits'+ptaskid).prepend(html);  //add html to board
  }
  if (pwhere == 'deleted'){
    $('#task_bits_deleted'+ptaskid).prepend(html);  //add html to board
  }
  
  if (pani){
    $('#bit'+pid).slideDown('slow');  //make html visible
    task_style(ptaskid);
  } else {
    $('#bit'+pid).show(0);  //make html visible
  }

  //Add hint:
  $('#bit'+pid).find('.cite_info_sort').attr('original-title','Using Quicksort:<br>Stop. Sorting. Tasks.<br> Do. Tasks.<br> Now.');
  $('#bit'+pid).find('.cite_info_sort').tipsy({gravity: 'w',html: true}); 
}

function html_line(pwidth,pcolor,pinfo){
  //create html
  iwidth = pwidth * 201;
  swidth = iwidth + '';
  html = '<div id="div_line'+pcolor+'" style="width:'+swidth+'px;background-color:#'+pcolor+';"></div>';
  $('#div_html_line').append(html);
  $('#div_line'+pcolor).attr('original-title',pinfo);
  $('#div_line'+pcolor).tipsy({gravity: 's'}); 
  //$('#div_line'+pcolor).css('-moz-box-shadow','0px 5px 5px #'+pcolor);
  //$('#div_line'+pcolor).css('-webkit-box-shadow','0px 5px 5px #'+pcolor);
  //$('#div_line'+pcolor).css('box-shadow','0px 5px 5px #'+pcolor);
}


// Task Overview ---------------------------------------------------------------------------------------------
// needs update everytime called
function task_overview(){
    $('#div_overview').empty();
    $('.p_task_caption').each(function(index) {
      taskid =  $(this).attr('taskid');
      html = ('<a href="javascript:task_focus('+taskid +','+index +');">' + index + ': ' + $(this).text() + '</a>');
      $('#div_overview').append(html);
    });
}

// Space Overview ---------------------------------------------------------------------------------------------
// needs update only once
function space_overview_add(pid, pname, pdescription){
  html = '<a href="#'+pid+'" onClick="space_overview_set(\''+pid+'\');">'+pname+'</a> ';
  $('#div_space_overview').append(html);  
}

function space_overview_set(pid){
  $('#div_body').empty();
  space_init();
  set_space(pid);
}



// Spaces---------------------------------------------------------------------------------------------

//
// Show List of all taskspaces
//

function space_init(){
  //load tasks
 gspace = '';
 gaTasks = [];
 $('#div_html_line').empty();
 $('#div_html_line').css('width','100%');
 $('#div_body').css('width','0px');
} 

//
// Load list of all available taskspaces
//

function space_init_load(){ 
 $('#div_spaces').empty();
 $('#div_space_overview').empty();
 AjaxResp = $.ajax({
      url: "/spaces",
      global: true,
      type: "GET",
      success: function(data){
        $('#div_body').empty();
		var sdata = data;
        if (sdata != ''){
         adatalines = data.split(gdlm2);
         for (var i in adatalines) {
           adata = adatalines[i].split(gdlm);
           id = adata[0];
           name = adata[1];
           description = adata[2];
           space_add(id,name,description);
		   space_overview_add(id,name,description);
         }
        } else {
		  $('#div_no_spaces').html('No spaces available');
		}
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
      }
   }
  ).responseText;
}

//
// Create new TaskSpace
//

function space_create(){
  AjaxResp = $.ajax({
      url: "/space/new",
      global: true,
      type: "POST",
      data: $('#form_space_new').serialize(),
      success: function(data){
         adata = data.split(gdlm);
         id = adata[0];
         name = adata[1];
         description = adata[2];
         space_add(id,name,description);
		 //clear form
		 $('#div_no_spaces').empty();
		 $('#form_space_new :input').val("");
		 $('#form_space_new :textarea').val("");
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
      }
   }
  ).responseText;
  return false;
}

//
// Show Space Overview - Spaces must be loaded before already
//
function space_overview_page(){
  $('#div_body').show('fast',function () {
             $('#div_body').empty();
			 task_overview();
			 space_init();
			 $('#div_space').show('fast');
  });
}



//
// Tasks ------------------------------------------------------------------
//

//
// Focus Task Textarea
//


function task_focus(ptaskid,position){
  $('#ta_bit_new'+ptaskid).focus();
  $(document).scrollLeft(position * giBitWidth );
  $('#task'+ptaskid).fadeTo("fast", 1);
  task_overview();
}


//
// Initialize Tasks
//

function task_init(){
  //load tasks
 AjaxResp = $.ajax({
      url: "/space/"+gspace+"/streams",
      global: true,
      type: "GET",
      success: function(data){
        var sdata = data;
        if (sdata != ''){
         adatalines = data.split(gdlm2);
         for (var i in adatalines) {
           adata = adatalines[i].split(gdlm);
           id = adata[0];
           msg = adata[1];
           owner = '';//adata[2];
           created = '';//adata[3];
           ani = false;
           if (adatalines.length-1 == i){ani = true; gbTaskInfo = true;}
           task_add(ani,id,msg,owner,created);
           bit_init(id);
         }
        }
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
      }
   }
  ).responseText;
}



//
// Put Task to First Position
//
function task_move(pid,pdir){
  dir = '';
  if (pdir == '-x') {dir = 'later'}
  if (pdir == '+x') {dir = 'now'}
  if (dir == '') {dir = 'now'}
  
  $('#col'+pid).hide(1,function () {
    AjaxResp = $.ajax({
      url: "/space/"+gspace+"/stream/"+pid+"/"+dir,
      global: true,
      type: "POST",
      success: function(msg){
         if (msg == '0'){
           if (pdir == '+x'){
             $('#div_body').prepend($('#col'+pid));
           }
           if (pdir == '-x'){
             $('#div_body').append($('#col'+pid));
           }
           $('#col'+pid).show('slow',function () {
             task_style(pid);
           });
           window.scrollTo(1,1);     
         } else {
           alert('Changing Position failed. Please reload page and try again. Contact support if problem persists.');
         }
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
         $('#col'+pid).show(0);
      }
    }
  ).responseText;
 });
}


//
// Delete a task
//
function task_del(pid){
 var answer = confirm ("Really delete this task?")
 if (answer) {

  AjaxResp = $.ajax({
      url: "/space/"+gspace+"/stream/"+pid+"/done",
      global: true,
      type: "POST",
      success: function(msg){
         if (msg == '0'){
           //$('#col'+pid).hide('slow',function () { //does not work in Chrome
             $('#col'+pid).remove();
             task_style(pid);
           //}); //does not work in Chrome
         } else {
           alert('Deletion failed: '+msg+'./n Please reload page and try again. Contact support if problem persists.');
         }
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
      }
   }
  ).responseText;
 }
}


//
// Create a task
//

function task_create(){
  if (gspace != '') {
  msg = jQuery.trim($('#ta_task_new').val());
  $('#ta_task_new').val('');
  if (msg == '') msg ='Task without description...';

  user = guser;

  AjaxResp = $.ajax({
      url: "/space/"+gspace+"/stream/new",
      global: true,
      type: "POST",
      data: ({name: msg}),
      success: function(data){
         //alert('Success: '+ data);
         adata = data.split(gdlm);
         id = adata[0];
         msg = adata[1];
         owner = '';//adata[2];
         created = '';//adata[3];
         gbTaskInfo = true;
         task_add(true,id,msg,owner,created);
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
      }
   }
  ).responseText;
  } else {
    alert ("Please select or create a TaskSpace before creating a new TaskStream.");
  }
}


//
// Style Tasks
//

function task_style(ptaskid){

 // for each task
 var gnFV = 10;
 $('#div_body').children().filter(".div_col").each(function() {
  var nFV = Math.round(gnFV)/10;
  $(this).fadeTo("fast", nFV );

  $(this).unbind('mouseenter');
  $(this).unbind('mouseleave');
  $(this).mouseenter(function () {
    $(this).fadeTo("fast", 1);
  });

  $(this).focus(function () {
    $(this).fadeTo("fast", 1);
  });

  $(this).mouseleave(function () {
    $(this).fadeTo("fast", nFV);
  });

  if (gnFV>2){gnFV=gnFV-2;}

 });


 $('#div_body').find(".not_first_col").css("visibility","");
 $('#div_body').find(".not_last_col").css("visibility","");

 //hide not needed buttons
 $('#div_body').children().filter(".div_col").first().find(".not_first_col").css("visibility","hidden");
 $('#div_body').children().filter(".div_col").last().find(".not_last_col").css("visibility","hidden");


 // for each bit
 var gnFV = 10;

 $('#task_bits'+ptaskid).children().filter(".div_bit").each(function() {
  var nFV = Math.round(gnFV)/10;
  $(this).fadeTo("fast", nFV );
 
  $(this).unbind('mouseenter');
  $(this).unbind('mouseleave');
  $(this).mouseenter(function () {
    $(this).fadeTo("fast", 1);
  });

  $(this).mouseleave(function () {
    $(this).fadeTo("fast", nFV);
  });

  if (gnFV>2){gnFV=gnFV-2;}
 });

 // special highlight for first bit
 $("#task_bits"+ptaskid).children().removeClass('div_bit_first');
 $("#task_bits"+ptaskid).children().first().addClass('div_bit_first');


 $("#task_bits"+ptaskid).find("button").css("visibility","");

 //hide not needed buttons
 $("#task_bits"+ptaskid).children().first().children().filter(".not_first").css("visibility","hidden");
 $("#task_bits"+ptaskid).children().last().children().filter(".not_last").css("visibility","hidden");


 //$(".div_bit").removeClass('div_bit_first');
 //$(".div_bit:first").addClass('div_bit_first');

 //Update all dates
 $(".span_bit_date").prettyDate();

}

// Bits ---------------------------------------------------------------------------------------------

//
// Initialize Bits
//

function bit_init(ptask_id){
  //delete existing bits
  $('#task_bits'+ptask_id).empty();
  //load bits
 AjaxResp = $.ajax({
      url: "/space/"+gspace+"/stream/"+ptask_id+"/bits",
      global: true,
      type: "GET",
      success: function(data){
        var sdata = data;
        if (sdata.substr(0,2) != '-1'){
         adatalines = data.split(gdlm2);
         for (var i in adatalines) {
           adata = adatalines[i].split(gdlm);
           task_id = adata[0];
           id = adata[1];
           msg = adata[2];
           owner = adata[3];
           created = adata[4];
           ani = false;
           if (adatalines.length-1 == i){ani = true;}
           bit_add(ani,task_id,id,msg,owner,created,'init' );
         }
         //task_style(ptask_id);
        }
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
      }
   }
  ).responseText;
}


//
// Show deleted Bits
//

function bit_init_deleted(ptask_id){
 //delete existing bits
 $('#task_bits_deleted'+ptask_id).empty();
 //load bits
 AjaxResp = $.ajax({
      url: "/space/"+gspace+"/stream/"+ptask_id+"/bitsdone",
      global: true,
      type: "GET",
      success: function(data){
	    if (data.substr(1,2) != '-1' && data != '') {
         adatalines = data.split(gdlm2);
         for (var i in adatalines) {
           adata = adatalines[i].split(gdlm);
		   //alert(adatalines[i]); //DEBUG
           task_id = adata[0];
           id = adata[1];
           msg = adata[2];
           owner = adata[3];
           created = adata[4];
           $('#span_bit_close_del'+task_id).css('visibility','');
           $('#task_bits_deleted'+task_id).css('visibility','');
           bit_add(true,task_id,id,msg,owner,created,'deleted');
         }
         task_style(ptask_id);
        }		
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
      }
   }
  ).responseText;
}


//
// Hide deleted bites
//

function bit_close_deleted(ptask_id){
 //delete existing bits
 $('#task_bits_deleted'+ptask_id).empty();
 $('#span_bit_close_del'+ptask_id).css('visibility','hidden');
 $('#task_bits_deleted'+ptask_id).css('visibility','hidden');
}


//
// Put Bit to top (set sort id to highest of task for bit
//
function bit_move(pid,ptaskid,pdir){
  $('#bit'+pid).show('slow'); 
  dir = '';
  if (pdir == '-x') {dir = 'later'}
  if (pdir == '+x') {dir = 'now'}
  if (dir == '') {dir = 'now'}
  
  //ptaskid
  AjaxResp = $.ajax({
      url: "/space/"+gspace+"/stream/"+ptaskid+"/bit/"+pid+"/"+dir,
      global: true,
      type: "POST",
      success: function(msg){
         if (msg == '0'){
           $('#bit'+pid).hide(0);
           if (pdir == '+x'){
             $('#task_bits'+ptaskid).prepend($('#bit'+pid));
           }
           if (pdir == '-x'){
             $('#task_bits'+ptaskid).append($('#bit'+pid));
           }
           $('#bit'+pid).slideDown('slow'); 

           $('#bit'+pid).find('button').removeAttr("disabled"); //enable all buttons

           task_style(ptaskid);
         } else {
           alert('Changing position failed. Please reload page and try again. Contact support if problem persists.');
         }
      }
   }
  ).responseText;
}


//
// Delete a bit
//
function bit_del(ptaskid,pid){
  AjaxResp = $.ajax({
      url: "/space/"+gspace+"/stream/"+ptaskid+"/bit/"+pid+"/done",
      global: true,
      type: "POST",
      success: function(msg){
         if (msg == '0'){
           $('#bit'+pid).slideUp('slow',function () {
             $('#bit'+pid).remove();
             task_style(pid);
           });
         } else {
           alert('Deletion failed. Please reload page and try again. Contact support if problem persists.');
         }
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
      }
   }
  ).responseText;
}

//
// Create a bit
//
function bit_create(ptaskid){
  msg =  jQuery.trim($('#ta_bit_new'+ptaskid).val());
  $('#ta_bit_new'+ptaskid).val('');
  if (msg == '') msg ='Speechless...';

  user = guser;

  AjaxResp = $.ajax({
      url: "/space/"+gspace+"/stream/"+ptaskid+"/bit/new",
      global: true,
      type: "POST",
      data: ({text: msg}),
      success: function(data){
         //alert('Success: '+ data);
         adata = data.split(gdlm);
         task_id = adata[0];
         id = adata[1];
         msg = adata[2];
         owner = adata[3];
         created = adata[4];
         bit_add(true,task_id,id,msg,owner,created,'init');
         $('#col'+task_id).mouseenter()
      },
      error: function(xhr, settings, exception) {
         help_error(xhr, settings, exception);
      }
   }
  ).responseText;
}


// help functions ---------------------------

//
// Show Error
//
function help_error(xhr, settings, exception){
  alert('error in: ' + xhr.statusText + ' \\n'+'response:\\n' + xhr.responseText.substr(1,1000) + ' \\n'+'uri:\\n' + settings.uri);
}

//
// process text before printing in html
//
function n2br(str){
  try {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	newstr = str.replace(exp,"<a target=\"_blank\" href='$1'>$1</a>"); //replace link
    newstr = newstr.replace(/\n/g,'<br \>'); //replace new line
    return newstr; 
  } catch (err) {
    return str + ' - An error occured while trying to process text.';
  }
}
